<?php

include_once 'admin.php';

/**
 *抽奖活动
 */
class actLotteryController extends adminController
{
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * 活动添加编辑页
     */
    public function dolotteryInfo() {
        $rowData = null;
        
        if ($lid = common::request('l_id', 'G')) {
            $rowData    = $this->db->getRowTable('r_activity_lottery', [], 'id=' . $lid);
            $rowData['adRotMap'] = '';
            $awardRotateMap = !empty($rowData['award_rotate_map']) ? json_decode($rowData['award_rotate_map'], true) : [];
            
            if (!empty($awardRotateMap)) {
                $awardRotateMap = array_map(function($v){return implode(',', $v);}, $awardRotateMap['awardMap']);
                $rowData['adRotMap'] = implode(':', $awardRotateMap);   
            }
        }
        
        $this->view->assign('viewDatas', $rowData);
        $this->view->display('lotteryinfo');
    }
    
    /**
     * 插入或更新抽奖活动
     */
    public function dolotteryAddEdit() {
        $lotteryId      = common::request('lotteryId', 'P');
        $title          = common::request('title', 'P');
        $introduce      = common::request('introduce', 'P');
        $start_time     = strtotime(common::request('starttime', 'P'));
        $end_time       = strtotime(common::request('endtime', 'P'));
        $awarddesc      = common::request('awarddesc', 'P');
        $_FILES['awardimg']['error'] == 0 && $award_img = $this->load('qiniu')->uploadQiNiuImg('awardimg', 'lottery_award'.md5(time().$title));
        $_FILES['rotateimg']['error'] == 0 && $rotate_img = $this->load('qiniu')->uploadQiNiuImg('rotateimg', 'lottery_rotate'.md5(time().$title));
        $add_time       = empty($lotteryId) ? time() : null;
        $awarddesc      = explode(',', $awarddesc);
        $award_desc     = json_encode(array_filter($awarddesc));
        $mapInfo        = common::request('mapinfo', 'P');
        $mapInfoArr     = explode(':', $mapInfo);
        $mapInfo        = array_map(function($v){return explode(',', $v);}, $mapInfoArr);
        $mapInfoArr     = array_sum(array_map(function ($v){return count($v);}, $mapInfo));
        $award_rotate_map = json_encode([
            'trunkNum' => $mapInfoArr,
            'awardMap' => $mapInfo
        ]);
        $init_joins     = common::request('init_joins', 'P');
        $init_code_provide = common::request('init_code_provide', 'P');
        $rowValue       = compact('title', 'introduce', 'start_time', 'end_time', 'award_img', 'rotate_img', 'add_time', 'award_desc', 'award_rotate_map', 'init_joins', 'init_code_provide');
        !$lotteryId && $rowValue = array_filter($rowValue); //新加活动去除空值

        $ret            = $lotteryId 
                ? $this->db->updateRowTable('r_activity_lottery', array_merge($rowValue,['id' => $lotteryId])) 
                : $this->db->insertRowTable('r_activity_lottery', $rowValue);  //插入或者更新
        
        if ($ret) {
            if ($lotteryId) {
                echo "更新成功，&nbsp;&nbsp;&nbsp;<a href='?c=actLottery&a=lotteryinfo&l_id={$lotteryId}'>查看活动详情</a>";
            } else {
                echo "添加成功，&nbsp;&nbsp;&nbsp;<a href='?c=actLottery&a=lotteryinfo&l_id={$ret}'>查看活动详情</a>";
            }
            exit;
        } else {
            echo "操作失败&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='".$_SERVER['HTTP_REFERER']."'>回到上一页</a>";
            exit;
        }   
    }
    
    /**
     * 抽奖活动列表
     */ 
    public function dolotteryList() {
        $p = common::request('p', 'G', 1);
        $p = intval($p);

        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 10;
        $num = $this->db->getCol('select count(1)  from r_activity_lottery');
        $lotteryList = $this->db->getAll(
            "select id,title,start_time,end_time,init_joins,init_code_provide from r_activity_lottery order by id DESC limit " . ($p - 1) * $listNum . ',' . $listNum
        );

        $page = new Page($num['0'], $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('lotteryList', $lotteryList);
        $this->view->assign('hosts', "http://".$this->config['host']);
        $this->view->display('lotterylist');
    }
    
    /**
     * 抽奖码页
     */
    public function docodeInfo() {
        $p = common::request('p', 'G', 1);
        $lid = common::request('lid', 'G', 0);
        $p = intval($p);
        
        if (empty($lid)) {
            exit('活动ID有误');
        }

        $actInfo = $this->db->getRowTable('r_activity_lottery', ['title', 'award_desc'], 'id=' . $lid);
        $awardInfo = json_decode($actInfo['award_desc'], true);
        $awardLevel = [];
        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 10;
        $codeList = [];
        $sendNum = 0;
        $num = $this->db->getCol('select count(1)  from r_activity_lottery_code where lid=' . $lid);
        
        if ($num['0']) {
            if (!empty($awardInfo)) {
                foreach ($awardInfo as $ak => $av) {
                    $awardLevel[] = $this->_nunToStr($ak+1) . '等奖';
                }
            }
            
            $tnum = $this->db->getCol('select count(1)  from r_activity_lottery_code where lid=' . $lid . ' and ucid<>0');
            $sendNum = $tnum['0'];
            $codeList = $this->db->getAll(
                "select * from r_activity_lottery_code where lid={$lid} limit " . ($p - 1) * $listNum . ',' . $listNum
            );
                
           foreach ($codeList as $ck => $cv) {
               $codeList[$ck]['uid'] = null;
               $codeList[$ck]['uname'] = '';
               $codeList[$ck]['phone'] = '';
               $codeList[$ck]['prize_desc'] = $cv['prize_level'] ? $this->_nunToStr($cv['prize_level']) . '等奖' : '未设置';
               
               if ($cv['ucid']) {
                   $uInfo = $this->db->getRowTable('r_activity_lottery_user', ['uid', 'realname', 'phone'], 'id=' . $cv['ucid']);
                   
                   if (!empty($uInfo)) {
                        $codeList[$ck]['uid'] = $uInfo['uid'];
                        $codeList[$ck]['uname'] = $uInfo['realname'];
                        $codeList[$ck]['phone'] = $uInfo['phone'];
                   }
               }
           }
        }
        
        $page = new Page($num['0'], $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('actTitle', $actInfo['title']);
        $this->view->assign('codeTotal', $num['0']);
        $this->view->assign('codeSend', $sendNum);
        $this->view->assign('codeList', $codeList);
        $this->view->assign('lid', $lid);
        $this->view->assign('awardLevel', json_encode($awardLevel));
        $this->view->display('drawcodelist');
    }
    
    /**
     * 中奖用户列表
     */
    public function dolotteryPrizeUserList() {
        $p          = common::request('p', 'G', 1);
        $export     = common::request('export', 'G');
        $lid        = common::request('lid', 'G');
        $uName      = common::request('uName', 'R');
        $uUid       = common::request('uUid', 'R');
        $uPhone     = common::request('uPhone', 'R');
        $prizeLevel = common::request('prizeLevel', 'R');
        $actInfo    = $this->db->getRowTable('r_activity_lottery', ['title', 'award_desc'], 'id=' . $lid);
        $awardInfo  = json_decode($actInfo['award_desc'], true);
        $queryParam = array_filter(compact('uName', 'uUid', 'uPhone', 'prizeLevel', 'lid'));
        $awardLevel = [];
        $where = 'c.lid=' . $lid;
      
        //设置查询条件
        !empty($uName) && $where .= ' and u.realname like "%' . $uName . '%"';
        !empty($uUid) && $where .= ' and u.uid=' . $uUid;
        !empty($prizeLevel) && $where .= ' and c.prize_level=' . $prizeLevel;
        !empty($uPhone) && $where .= ' and u.phone="' . $uPhone . '"';
        
        if (!empty($awardInfo)) {
            foreach ($awardInfo as $ak => $av) {
                $awardLevel[] = $this->_nunToStr($ak+1) . '等奖';
            }
        }
        
        if ($export) {
            $userList = $this->db->getAll(
                    "select c.prize_level,u.uid,u.realname,u.phone,u.detail_addr from r_activity_lottery_code c inner join r_activity_lottery_user u on c.ucid=u.id where {$where} and c.prize_level<>0 and c.ucid<>0 and c.is_draw=1 order by u.id asc "
                );
            
            if (!empty($userList)) {
//                foreach ($userList as $ck => $cv) {
//                    $uids[] = $cv['uid'];
//                    $userList[$ck]['prize_desc'] = $this->_nunToStr($cv['prize_level']) . '等奖';
//                }
//
//                $userInfos = $this->db->getAll('select uid,nickname from r_user where uid in (' . implode(',', array_unique($uids)) . ')');
//
//                foreach ($userInfos as $uv) {
//                    $uInfos[$uv['uid']] = $uv['nickname'];
//                }

                $excelstr  = '<table border="1">';
                $excelstr .= '<tr><td colspan="5" align="center">' . $actInfo['title'] . '中奖用户列表</td></tr>';
                $excelstr .= '<tr><td align="center">奖项</td><td align="center">用户ID</td><td align="center">用户姓名</td><td align="center">用户手机号</td><td align="center">用户详细地址</td></tr>';

                foreach ($userList as $uv) {
                    $excelstr .= '<tr><td align="center">' . $this->_nunToStr($uv['prize_level']) . '等奖</td><td align="center">' . $uv['uid'] . '</td><td align="center">' . $uv['realname'] .
                        '</td><td align="center">' . $uv['phone'] . '</td><td align="center">' . $uv['detail_addr'] . '</td></tr>';
                }
                
                $excelstr .= '</table>';
                
                //处理ie中文标题乱码
                if(preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {  
                    $title = str_replace('+','%20',urlencode($actInfo['title'] . '中奖用户列表'));  
                } 

                header("Content-type:application/vnd.ms-excel;charset=UTF-8"); 
                header("Content-Disposition:attachment; filename=" . $actInfo['title'] . "中奖用户列表.xls");
                echo iconv("UTF-8", "GBK", $excelstr);
                exit;
            } else {
                exit('no data <a href="'. $_SERVER['HTTP_REFERER'] . '">go back</a>');
            }
        } else {
            //分页
            require FILE . 'lib/page.class.php';
            $listNum = 15;
            $userList = $uInfos = [];
            $num = $this->db->getCol('select count(1)  from r_activity_lottery_code c inner join r_activity_lottery_user u on c.ucid=u.id where ' . $where . ' and c.prize_level<>0 and c.ucid<>0 and c.is_draw=1');  

            if ($num['0'] > 0) {

                $userList = $this->db->getAll(
                    "select c.prize_level,u.uid,u.realname,u.phone,u.detail_addr from r_activity_lottery_code c inner join r_activity_lottery_user u on c.ucid=u.id where {$where} and c.prize_level<>0 and c.ucid<>0 and c.is_draw=1 order by u.id asc limit " . ($p - 1) * $listNum . ',' . $listNum
                );
                $uids = [];

               foreach ($userList as $ck => $cv) {
                   $uids[] = $cv['uid'];
                   $userList[$ck]['prize_desc'] = $this->_nunToStr($cv['prize_level']) . '等奖';
               }

               $userInfos = $this->db->getAll('select uid,nickname from r_user where uid in (' . implode(',', array_unique($uids)) . ')');

               foreach ($userInfos as $uv) {
                   $uInfos[$uv['uid']] = $uv['nickname'];
               }
            }

            $page = new Page($num['0'], $listNum, '&' . http_build_query($queryParam));
            $pageStr = $page->show();
            $this->view->assign('pageStr', $pageStr);
            $this->view->assign('userList', $userList);
            $this->view->assign('lid', $lid);
            $this->view->assign('uInfos', $uInfos);
            $this->view->assign('awardLevel', json_encode($awardLevel));
            $this->view->assign('queryParam', $queryParam);
            $this->view->display('prizeuserlist');
        }
    }
    
    /**
     * 抽奖码生成
     */
    public function dogenerateCode() {
        $lid = common::request('lid', 'P');
        $num = common::request('num', 'P');
        
        if ($lid && $num) {
            $codeArr = [];
            
            //生成指定数量的抽奖码
            while($num-- > 0 ) {
                $codeArr[] = $this->_generateCode();
            }
            
            //抽奖码批量入库
            if (!empty($codeArr)) {
                $sqlPre = 'insert into r_activity_lottery_code (lid,code,add_time) values ';
                $tNum = 0;
                
                if (($tNum = count($codeArr)) > 1000) {
                    $times = ceil($tNum / 1000);
                    
                    for($i = 0; $i < $times; $i++) {
                        $tArr = array_slice($codeArr, $i * 1000, 1000);
                        $sqlSuf = '';

                        foreach ($tArr as $ck => $cv) {
                            if ($ck == 0) {
                                $sqlSuf .= '(' . $lid . ',"' . $cv . '",' . time() . ')';
                            } else {
                                $sqlSuf .= ',(' . $lid . ',"' . $cv . '",' . time() . ')';
                            }
                        }

                        $ret = $this->db->query($sqlPre.$sqlSuf);
                        
                        if (!$ret && $i == 0) {
                            exit(json_encode(['code' => 2, 'msg' => '抽奖码生成失败，本次生成0个抽奖码，请重试']));
                        } else if (!$ret) {
                            exit(json_encode(['code' => 0, 'msg' => '部分抽奖码生成失败，本次成功生成' . ($i * 1000) . '个抽奖码']));
                        }
                    }
                    
                    exit(json_encode(['code' => 0, 'msg' => '成功生成' . $tNum . '个抽奖码']));
                } else {
                    $sqlSuf = '';
                    
                    foreach ($codeArr as $ck => $cv) {
                        if ($ck == 0) {
                            $sqlSuf .= '(' . $lid . ',"' . $cv . '",' . time() . ')';
                        } else {
                            $sqlSuf .= ',(' . $lid . ',"' . $cv . '",' . time() . ')';
                        }
                    }
                    
                    $ret = $this->db->query($sqlPre.$sqlSuf);
                    
                    if ($ret) {
                        exit(json_encode(['code' => 0, 'msg' => '成功生成' . $tNum . '个抽奖码']));
                    } else {
                        exit(json_encode(['code' => 2, 'msg' => '抽奖码生成失败，本次生成0个抽奖码，请重试']));
                    }
                }
            }
        } else {
            exit(json_encode(['code' => 1, 'msg' => '参数有误']));
        }
    }
    
    /**
     * 更新单个抽奖码中奖信息
     */
    public function doupdateCodeInfo() {
        $id = common::request('id', 'P');
        $lid = common::request('lid', 'P');
        $prize_level = common::request('prize_level', 'P', 0);
        $uid = common::request('uid', 'P');
        $phone = common::request('phone', 'P');
        $upStatus = true;
        
        if (empty($uid) || empty($phone)) {
            $upStatus = $this->db->update('update r_activity_lottery_code set prize_level=' . $prize_level . ' where id=' . $id . ' and is_draw=0');
        } else {
            $lUser = $this->db->getRowTable('r_activity_lottery_user', ['id'], 'uid=' . $uid . ' and phone="' . $phone . '"');
            
            if (!empty($lUser)) {
//                $uCode = $this->db->getRowTable('r_activity_lottery_code', ['id'], 'ucid=' . $lUser['id'] . ' and lid=' . $lid);
//                
//                if (!empty($uCode) && $uCode['id'] != $id) {
//                    exit(json_encode(['code' => 2, 'msg' => '该手机用户已参加该抽奖活动']));
//                }

                $upStatus = $this->db->update('update r_activity_lottery_code set prize_level=' . $prize_level . ',ucid=' . $lUser['id'] . ' where id=' . $id . ' and is_draw=0');
            } else {
                $uret = $this->db->insertRowTable('r_activity_lottery_user', ['uid' => $uid, 'phone' => $phone, 'add_time' => time()]);
                
                if ($uret) {
                    $upStatus = $this->db->update('update r_activity_lottery_code set prize_level=' . $prize_level . ',ucid=' . $uret . ' where id=' . $id . ' and is_draw=0');
                } else {
                    $upStatus = false;
                }
            }
        }
        
        if ($upStatus !== false) {
            exit(json_encode(['code' => 0, 'msg' => '设置成功']));
        } else {
            exit(json_encode(['code' => 1, 'msg' => '设置失败']));
        }
    }
    
    public function doprizeSet(){
        $idSub = common::request('idSub', 'P');
        $idSup = common::request('idSup', 'P');
        $gOrder = common::request('gOrder', 'P');
        $gCount = common::request('gCount', 'P');
        $gPrize = common::request('gPrize', 'P', 0);
        $lid = common::request('lid', 'P');
        $upStatus = true;
        $sql = '';
        
        if ($idSub || $idSup) {
            if ($idSub && $idSup) {
                if ($idSup < $idSub) {
                    $tmp = $idSub;
                    $idSub = $idSup;
                    $idSup = $tmp;
                }
                
                if ($gOrder == 1) {
                    $sql = 'update r_activity_lottery_code set prize_level=' . $gPrize . ' where lid=' . $lid . ' and id between ' . $idSub . ' and ' . $idSup .  ' and is_draw=0 and ucid=0 and prize_level=0 limit ' . $gCount;
                } else if ($gOrder == 2) {
                    $tDatas = $this->db->getAll('select id from r_activity_lottery_code where lid=' . $lid . ' and id between ' . $idSub . ' and ' . $idSup . ' and is_draw=0 and ucid=0 and prize_level=0 order by id desc limit ' . $gCount );
                    $idArr = [];

                    foreach($tDatas as $dv) {
                        $idArr[] = $dv['id'];
                    }

                    if (!empty($idArr)) {
                        $sql = 'update r_activity_lottery_code set prize_level=' . $gPrize . ' where id in ( '. implode(',', $idArr) . ')';
                    }
                } else if ($gOrder == 3) { //伪随机
                    $tDatas = $this->db->getAll('select id from r_activity_lottery_code  where lid=' . $lid . ' and id between ' . $idSub . ' and ' . $idSup .  ' and is_draw=0 and ucid=0 and prize_level=0 limit 10000');
                    $idArr = [];

                    foreach($tDatas as $dv) {
                        $idArr[] = $dv['id'];
                    }

                    if (!empty($idArr)) {
                        $arrNum = count($idArr);
                        $wArr = [];

                        if ($arrNum <= $gCount) {
                            $wArr = $idArr;
                        } else {
                            shuffle($idArr);
                            $wArr = array_slice($idArr, 0, $gCount);
//                            while ($gCount-- > 0) {
//                                $wArr[] = $idArr[rand(0, $arrNum - 1)];
//                            }
                        }

                        $sql = 'update r_activity_lottery_code set prize_level=' . $gPrize . ' where id in (' . implode(',', $wArr) . ')';
                    }
                } else {

                }
                
            } else if ($idSub) {
                $sql = 'update r_activity_lottery_code set prize_level=' . $gPrize . ' where id=' . $idSub .  ' and lid=' . $lid . ' and is_draw=0 and ucid=0';
            } else {
                $sql = 'update r_activity_lottery_code set prize_level=' . $gPrize . ' where id=' . $idSup .  ' and lid=' . $lid . ' and is_draw=0 and ucid=0';
            }        
        } else {
            if ($gOrder == 1) {
                $sql = 'update r_activity_lottery_code set prize_level=' . $gPrize . ' where lid=' . $lid . ' and is_draw=0 and ucid=0 and prize_level=0 limit ' . $gCount;
            } else if ($gOrder == 2) {
                $tDatas = $this->db->getAll('select id from r_activity_lottery_code where lid=' . $lid . ' and is_draw=0 and ucid=0 and prize_level=0 order by id desc limit ' . $gCount );
                $idArr = [];
                
                foreach($tDatas as $dv) {
                    $idArr[] = $dv['id'];
                }
                
                if (!empty($idArr)) {
                    $sql = 'update r_activity_lottery_code set prize_level=' . $gPrize . ' where id in ( '. implode(',', $idArr) . ')';
                }
            } else if ($gOrder == 3) { //伪随机
                $tDatas = $this->db->getAll('select id from r_activity_lottery_code  where lid=' . $lid . ' and is_draw=0 and ucid=0 and prize_level=0 limit 10000');
                $idArr = [];
                
                foreach($tDatas as $dv) {
                    $idArr[] = $dv['id'];
                }
                
                if (!empty($idArr)) {
                    $arrNum = count($idArr);
                    $wArr = [];
                    
                    if ($arrNum <= $gCount) {
                        $wArr = $idArr;
                    } else {
                        shuffle($idArr);
                        $wArr = array_slice($idArr, 0, $gCount); 
//                        while ($gCount-- > 0) {
//                            $wArr[] = $idArr[rand(0, $arrNum - 1)];
//                        }
                    }
                    
                    $sql = 'update r_activity_lottery_code set prize_level=' . $gPrize . ' where id in (' . implode(',', $wArr) . ')';
                }
            } else {
                
            }
        }
        
        if ($sql) {
            $upStatus = $this->db->update($sql);
        } else {
            $upStatus = false;
        }
        
        if ($upStatus === false) {
            exit(json_encode(['code' => 1, 'msg' => '设置失败']));
        } else {
            exit(json_encode(['code' => 0, 'msg' => '设置成功']));
        }
    }
    
    /**
     * 生成固定长度随机字符
     * @param numeric $len 生成的随机字符长度
     * @return string 随机字符
     */
    protected function _generateCode($len = 10) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $code = base_convert(uniqid(), 16, 36);
        
        if ($len > 10) {
            $steps = $len - 10;
            
            for ( $i = 0; $i < $steps; $i++ ) {   
                $code .= $chars[ mt_rand(0, strlen($chars) - 1) ];  
            }  
        }
        
        return $code;  
    }
    
    /**
     * 1-10数字转成对应中文一到十
     * @param numeric $num
     * @return string
     */
    private function _nunToStr($num){
        switch ($num):
            case 1:
                return '一';
                break;
            case 2:
                return '二';
                break;
            case 3:
                return '三';
                break;
            case 4:
                return '四';
                break;
            case 5:
                return '五';
                break;
            case 6:
                return '六';
                break;
             case 7:
                return '七';
                break;
            case 8:
                return '八';
                break;
            case 9:
                return '九';
                break;
            case 10:
                return '十';
                break;
            default:
                return $num;
                break;
        endswitch;
    }
}
